package com.siki.config.filterConfig.loginStatus;

import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.siki.config.filterConfig.jwtConfig.TokenFactory;
import com.siki.mapper.UserMapper;
import com.siki.pojo.commonEntity.SysUser;
import com.siki.utils.Deprecated.JsonResult;
import com.siki.utils.JsonInfoReturn;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

/**
 * 登录成功处理逻辑
 *
 * @Author Siki
 * @Date 2020/6/5
 */
@Component
public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    TokenFactory tokenFactory;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {

        //更新用户表上次登录时间、更新人、更新时间等字段
        User userDetails = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        SysUser sysUser = Optional.ofNullable(userMapper.selectById(userDetails.getUsername())).orElseThrow(()->new RuntimeException("找不到"));


        //这里是把生成的token丢进去登录成功的信息中
        String token = tokenFactory.getToken(sysUser);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token",token);

        //返回json数据
        JsonInfoReturn result = JsonInfoReturn.success(jsonObject);

        //处理编码方式，防止中文乱码的情况
        httpServletResponse.setContentType("text/json;charset=utf-8");
        //塞到HttpServletResponse中返回给前台
        httpServletResponse.getWriter().write(JSON.toJSONString(result));
    }
}
